#include "widget.h"
#include "ui_widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);

    //使用定时器
    timer=new QTimer();
    //定时器有一个timeout信号
    //信号槽（信号和对应函数关联起来）
    connect(timer,SIGNAL(timeout()),this,SLOT(timeout()));
}

Widget::~Widget()
{
    delete ui;
}
//控制方向
void Widget::keyPressEvent(QKeyEvent *event){
    switch(event->key()){
    case Qt::Key_Up:
        if(moveFlag!=DIR_DOWN){
        moveFlag=DIR_UP;
        }
        break;
    case Qt::Key_Down:
        if(moveFlag!=DIR_UP){
        moveFlag=DIR_DOWN;
        }
        break;
    case Qt::Key_Right:
        if(moveFlag!=DIR_LEFT){
        moveFlag=DIR_RIGHT;
        }
        break;
    case Qt::Key_Left:
        if(moveFlag!=DIR_RIGHT){
        moveFlag=DIR_LEFT;
        }
        break;
    case Qt::Key_Space:
        if(gameStart==false){
            gameStart=true;
            //启动定时器
            timer->start(time);
        }else{
            gameStart=false;
            timer->stop();
        }
        break;
    default:
        break;
    }
}


void Widget::timeout(){
    switch(moveFlag){
      case DIR_UP:
        //在顶部加一个小方块
        break;
      case DIR_DOWN:
        break;
      case DIR_RIGHT:
        break;
      case DIR_LEFT:
        break;
      default:
        break;
    }
}

void Widget::addTop(){
    QPointF leftTop;
    QPointF rightBotom;

    if(snake[0].y()-nodeHeight<0){
        leftTop =QPoint(snake[0].x(),this->height()-nodeHeight);
        rightBotom =QPoint(snake[0].x()+nodeWidth,this->height());
    }else{
        leftTop=QPointF(snake[0].x(),snake[0].y()-nodeHeight);
        rightBotom =snake[0].topRight();
    }

    snake.insert(0 , QRectF(leftTop,rightBotom));
}
